import { Component, PropsWithChildren } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import { AtButton, AtIcon } from 'taro-ui'
import Taro from '@tarojs/taro'
import './index.scss'
import { getFoodList, calculateStatus } from '../../services/foodService'

interface FoodItem {
  id: string
  name: string
  category: string
  quantity: number
  unit: string
  purchaseDate: string
  expiryDate: string
  status: 'normal' | 'low' | 'expiring'
  location?: string
  image?: string
}

interface CategoryStats {
  name: string
  count: number
  percentage: number
  emoji: string
}

interface LocationStats {
  name: string
  count: number
  percentage: number
  emoji: string
}

interface State {
  foodList: FoodItem[]
  categoryStats: CategoryStats[]
  locationStats: LocationStats[]
  totalItems: number
  expiringCount: number
  lowStockCount: number
  normalCount: number
}

export default class Statistics extends Component<PropsWithChildren, State> {
  constructor(props: PropsWithChildren) {
    super(props)
    this.state = {
      foodList: [],
      categoryStats: [],
      locationStats: [],
      totalItems: 0,
      expiringCount: 0,
      lowStockCount: 0,
      normalCount: 0
    }
  }

  componentDidMount() {
    this.loadStatistics()
  }

  loadStatistics = () => {
    const foodList = getFoodList()
    
    // 更新食材状态
    const updatedFoodList = foodList.map(item => ({
      ...item,
      status: calculateStatus(item.expiryDate)
    }))

    // 计算状态统计
    const expiringCount = updatedFoodList.filter(item => item.status === 'expiring').length
    const lowStockCount = updatedFoodList.filter(item => item.status === 'low').length
    const normalCount = updatedFoodList.filter(item => item.status === 'normal').length
    const totalItems = updatedFoodList.length

    // 计算分类统计
    const categoryMap = new Map<string, number>()
    updatedFoodList.forEach(item => {
      const category = item.category || '其他'
      categoryMap.set(category, (categoryMap.get(category) || 0) + 1)
    })

    const categoryStats: CategoryStats[] = Array.from(categoryMap.entries()).map(([name, count]) => ({
      name,
      count,
      percentage: totalItems > 0 ? Math.round((count / totalItems) * 100) : 0,
      emoji: this.getCategoryEmoji(name)
    })).sort((a, b) => b.count - a.count)

    // 计算位置统计
    const locationMap = new Map<string, number>()
    updatedFoodList.forEach(item => {
      const location = item.location || '未设置'
      locationMap.set(location, (locationMap.get(location) || 0) + 1)
    })

    const locationStats: LocationStats[] = Array.from(locationMap.entries()).map(([name, count]) => ({
      name,
      count,
      percentage: totalItems > 0 ? Math.round((count / totalItems) * 100) : 0,
      emoji: this.getLocationEmoji(name)
    })).sort((a, b) => b.count - a.count)

    this.setState({
      foodList: updatedFoodList,
      categoryStats,
      locationStats,
      totalItems,
      expiringCount,
      lowStockCount,
      normalCount
    })
  }

  getCategoryEmoji = (category: string) => {
    switch (category) {
      case '蔬菜': return '🥬'
      case '水果': return '🍎'
      case '肉类': return '🥩'
      case '主食': return '🍚'
      case '调料': return '🧂'
      case '蛋奶': return '🥚'
      default: return '🍱'
    }
  }

  getLocationEmoji = (location: string) => {
    switch (location) {
      case '冷冻': return '🧊'
      case '冷藏一层':
      case '冷藏二层':
      case '冷藏三层': return '❄️'
      case '客厅五斗柜':
      case '客厅置物柜':
      case '小房间': return '⚱️'
      default: return '📦'
    }
  }

  handleGoBack = () => {
    Taro.navigateBack()
  }

  handleGoToKitchen = () => {
    Taro.navigateTo({
      url: '/pages/kitchen/index'
    })
  }

  render() {
    const { 
      categoryStats, 
      locationStats, 
      totalItems, 
      expiringCount, 
      lowStockCount, 
      normalCount 
    } = this.state

    return (
      <View className='statistics-page'>
        <View className='animated-background'>
          <View className='floating-icons'>
            <Text className='float-icon' style={{animationDelay: '0s'}}>📊</Text>
            <Text className='float-icon' style={{animationDelay: '1s'}}>📈</Text>
            <Text className='float-icon' style={{animationDelay: '2s'}}>📉</Text>
            <Text className='float-icon' style={{animationDelay: '0.5s'}}>💹</Text>
            <Text className='float-icon' style={{animationDelay: '1.5s'}}>📋</Text>
            <Text className='float-icon' style={{animationDelay: '2.5s'}}>🔢</Text>
          </View>
        </View>

        {/* 顶部导航栏 */}
        <View className='top-navbar'>
          <View className='navbar-left'>
            <AtIcon 
              value='chevron-left' 
              size='24' 
              className='back-icon'
              onClick={this.handleGoBack}
            />
            <Text className='page-title'>智能统计</Text>
          </View>
          <View className='navbar-right'>
            <AtIcon 
              value='home' 
              size='20' 
              className='nav-icon'
              onClick={this.handleGoToKitchen}
            />
          </View>
        </View>

        <ScrollView className='statistics-content' scrollY>
          {/* 总览统计 */}
          <View className='overview-section'>
            <View className='overview-header'>
              <Text className='section-title'>📊 数据总览</Text>
              <Text className='section-subtitle'>食材库存全景分析</Text>
            </View>
            
            <View className='overview-cards'>
              <View className='overview-card total'>
                <View className='card-icon'>🛒</View>
                <View className='card-content'>
                  <Text className='card-number'>{totalItems}</Text>
                  <Text className='card-label'>总食材</Text>
                </View>
              </View>
            </View>
          </View>

          {/* 状态分布图表 */}
          <View className='chart-section'>
            <View className='chart-header'>
              <Text className='section-title'>📈 状态分布</Text>
              <Text className='section-subtitle'>食材健康度一览</Text>
            </View>
            
            <View className='status-chart'>
              <View className='chart-container'>
                {/* 环形图表 */}
                <View className='donut-chart-container'>
                  <View 
                    className='donut-chart'
                    style={{
                      background: totalItems > 0 ? 
                        `conic-gradient(
                          from 0deg,
                          #10b981 0deg ${(normalCount / totalItems) * 360}deg,
                          #f59e0b ${(normalCount / totalItems) * 360}deg ${((normalCount + lowStockCount) / totalItems) * 360}deg,
                          #ef4444 ${((normalCount + lowStockCount) / totalItems) * 360}deg 360deg
                        )` :
                        '#e5e7eb'
                    }}
                  >
                    <View className='donut-center'>
                      <Text className='donut-total'>{totalItems}</Text>
                      <Text className='donut-label'>总计</Text>
                    </View>
                  </View>
                  
                  {/* 图例 */}
                  <View className='chart-legend'>
                    <View className='legend-item normal'>
                      <View className='legend-color' />
                      <Text className='legend-text'>正常 ({normalCount})</Text>
                      <Text className='legend-percentage'>{totalItems > 0 ? Math.round((normalCount / totalItems) * 100) : 0}%</Text>
                    </View>
                    <View className='legend-item warning'>
                      <View className='legend-color' />
                      <Text className='legend-text'>关注 ({lowStockCount})</Text>
                      <Text className='legend-percentage'>{totalItems > 0 ? Math.round((lowStockCount / totalItems) * 100) : 0}%</Text>
                    </View>
                    <View className='legend-item danger'>
                      <View className='legend-color' />
                      <Text className='legend-text'>过期 ({expiringCount})</Text>
                      <Text className='legend-percentage'>{totalItems > 0 ? Math.round((expiringCount / totalItems) * 100) : 0}%</Text>
                    </View>
                  </View>
                </View>
                
                {/* 柱状图表 */}
                <View className='bar-chart-container'>
                  <View className='chart-bars'>
                    <View className='chart-bar-group'>
                      <View 
                        className='chart-bar normal'
                        style={{
                          height: totalItems > 0 ? 
                            (normalCount > 0 ? `${Math.max((normalCount / totalItems) * 100, 8)}%` : '2%') : 
                            '2%'
                        }}
                      />
                      <Text className='bar-label'>正常</Text>
                      <Text className='bar-value'>{normalCount}</Text>
                    </View>
                    
                    <View className='chart-bar-group'>
                      <View 
                        className='chart-bar warning'
                        style={{
                          height: totalItems > 0 ? 
                            (lowStockCount > 0 ? `${Math.max((lowStockCount / totalItems) * 100, 8)}%` : '2%') : 
                            '2%'
                        }}
                      />
                      <Text className='bar-label'>关注</Text>
                      <Text className='bar-value'>{lowStockCount}</Text>
                    </View>
                    
                    <View className='chart-bar-group'>
                      <View 
                        className='chart-bar danger'
                        style={{
                          height: totalItems > 0 ? 
                            (expiringCount > 0 ? `${Math.max((expiringCount / totalItems) * 100, 8)}%` : '2%') : 
                            '2%'
                        }}
                      />
                      <Text className='bar-label'>过期</Text>
                      <Text className='bar-value'>{expiringCount}</Text>
                    </View>
                  </View>
                </View>
              </View>
            </View>
          </View>

          {/* 分类统计 */}
          <View className='category-section'>
            <View className='section-header'>
              <Text className='section-title'>🏷️ 分类统计</Text>
              <Text className='section-subtitle'>按食材类型分布</Text>
            </View>
            
            <View className='stats-list'>
              {categoryStats.map((stat, index) => (
                <View key={stat.name} className='stat-item'>
                  <View className='stat-info'>
                    <Text className='stat-emoji'>{stat.emoji}</Text>
                    <View className='stat-text'>
                      <Text className='stat-name'>{stat.name}</Text>
                      <Text className='stat-count'>{stat.count} 种</Text>
                    </View>
                  </View>
                  <View className='stat-progress'>
                    <View className='progress-bar'>
                      <View 
                        className='progress-fill'
                        style={{
                          width: `${stat.percentage}%`,
                          backgroundColor: this.getProgressColor(index)
                        }}
                      />
                    </View>
                    <Text className='stat-percentage'>{stat.percentage}%</Text>
                  </View>
                </View>
              ))}
            </View>
          </View>

          {/* 位置统计 */}
          <View className='location-section'>
            <View className='section-header'>
              <Text className='section-title'>📍 位置统计</Text>
              <Text className='section-subtitle'>按存放位置分布</Text>
            </View>
            
            <View className='stats-list'>
              {locationStats.map((stat, index) => (
                <View key={stat.name} className='stat-item'>
                  <View className='stat-info'>
                    <Text className='stat-emoji'>{stat.emoji}</Text>
                    <View className='stat-text'>
                      <Text className='stat-name'>{stat.name}</Text>
                      <Text className='stat-count'>{stat.count} 种</Text>
                    </View>
                  </View>
                  <View className='stat-progress'>
                    <View className='progress-bar'>
                      <View 
                        className='progress-fill'
                        style={{
                          width: `${stat.percentage}%`,
                          backgroundColor: this.getProgressColor(index)
                        }}
                      />
                    </View>
                    <Text className='stat-percentage'>{stat.percentage}%</Text>
                  </View>
                </View>
              ))}
            </View>
          </View>

          {/* 数据为空时的提示 */}
          {totalItems === 0 && (
            <View className='empty-state'>
              <View className='empty-icon'>📊</View>
              <Text className='empty-title'>暂无统计数据</Text>
              <Text className='empty-subtitle'>添加一些食材后再来查看统计信息吧</Text>
              <AtButton 
                type='primary'
                className='go-add-btn'
                onClick={this.handleGoToKitchen}
              >
                去添加食材
              </AtButton>
            </View>
          )}
        </ScrollView>

        {/* 底部操作栏 */}
        <View className='bottom-actions'>
          <AtButton 
            type='primary'
            className='bottom-action-btn'
            onClick={this.handleGoToKitchen}
          >
            返回厨房管理
          </AtButton>
          <AtButton 
            className='bottom-action-btn secondary'
            onClick={() => {
              this.loadStatistics()
              Taro.showToast({
                title: '数据已刷新',
                icon: 'success'
              })
            }}
          >
            刷新数据
          </AtButton>
        </View>
      </View>
    )
  }

  getProgressColor = (index: number) => {
    const colors = ['#f59e0b', '#10b981', '#3b82f6', '#8b5cf6', '#ef4444', '#06b6d4']
    return colors[index % colors.length]
  }
}
